<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :on-change="changeAvatar"
    :auto-upload="false"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      avatarFile: null
    }
  },
  methods: {
    /**
     * 图片上传之前的检查
     * @param file 文件
     */
    beforeAvatarUpload(file) {
      // 支持 jpeg png gif bmp
      const fileType = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp']
      const isJPG = fileType.includes(file.type)
      // 文件大小：< 5MB
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 jpeg png gif bmp 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      console.log('运行了')
      return isJPG && isLt2M
    },
    /**
     * 文件状态改变时
     * @param params 文件选择器选择的对下稿
     */
    changeAvatar(params) {
      if (this.beforeAvatarUpload(params.raw)) {
        this.avatarFile = params.raw
        this.$emit('input', URL.createObjectURL(params.raw))
      }
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
